﻿using System.Net.Http;

namespace HttpClientLite;

/// <summary>
/// http相关帮助函数
/// </summary>
public class HttpHelper
{
    /// <summary>
    /// 克隆请求消息
    /// </summary>
    /// <param name="req"></param>
    /// <returns></returns>
    public static async Task<HttpRequestMessage> CloneAsync(HttpRequestMessage req)
    {
        HttpRequestMessage clone = new HttpRequestMessage(req.Method, req.RequestUri);

        var ms = new MemoryStream();

        if (req.Content is not null)
        {
            await req.Content.CopyToAsync(ms).ConfigureAwait(false);
            ms.Position = 0;
            clone.Content = new StreamContent(ms);

            foreach (var h in req.Content.Headers)
                clone.Content.Headers.Add(h.Key, h.Value);
        }

        clone.Version = req.Version;

#if NETCOREAPP
        foreach (KeyValuePair<string, object?> option in req.Options)
            clone.Options.Set(new HttpRequestOptionsKey<object?>(option.Key), option.Value);
#endif

        foreach (KeyValuePair<string, IEnumerable<string>> header in req.Headers)
            clone.Headers.TryAddWithoutValidation(header.Key, header.Value);

        return clone;
    }
}